﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
using System.Linq.Expressions;
using System.Data;

namespace ISRecord.Model
{
    public abstract class RepositoryBase<TEntity>:IDisposable
    {
        protected Sender2006Entities Context { get; set; }

        public abstract void Add(TEntity entity);
        public abstract void Delete(TEntity entity);
        public abstract TEntity GetByID(object id);
        public abstract IList<TEntity> GetAll();
        public abstract IQueryable<TEntity> Query(Expression<Func<TEntity, bool>> filter);
        /// <summary>
        /// Persists all updates to the data source and resets change tracking in the
        /// object context.
        /// </summary>
        public virtual void Save()
        {
            Context.SaveChanges();
        }
        bool disposed = false;
        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    if (Context != null)
                    {
                        Context.Dispose();
                    }
                }
            }
            disposed = true;
        }

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        public bool HasChanges
        {
            get 
            {
                return (
                    Context.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Added).Any() ||
                    Context.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Modified).Any() ||
                    Context.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Deleted).Any()
                       );
            }
        }
        public abstract void RefreshContext();
        public void ChangeEntityState(TEntity entity, EntityState state)
        {
            Context.ObjectStateManager.ChangeObjectState(entity, state);
        }
    }
}
